// 导航栏滚动效果
window.addEventListener('scroll', () => {
  const navbar = document.querySelector('.navbar');
  if (window.scrollY > 400) {
    navbar.classList.add('scrolled');
  } else {
    navbar.classList.remove('scrolled');
  }
});

// 导航栏透明度随滚动渐变
window.addEventListener('scroll', () => {
  const navbar = document.querySelector('.navbar');
  const maxScroll = 900; // 渐变最大滚动距离，拉大渐变区间
  const scrollY = Math.min(window.scrollY, maxScroll);
  const alpha = scrollY / maxScroll;
  // 渐变到深红色
  navbar.style.background = `rgba(139,26,26,${alpha})`;
});

// 移动端菜单切换
const menuToggle = document.getElementById('menuToggle');
const navLinks = document.getElementById('navLinks');

if (menuToggle && navLinks) {
  menuToggle.addEventListener('click', () => {
    navLinks.classList.toggle('active');
  });
}

// 动画触发函数
function handleScrollAnimation() {
  const animatedElements = document.querySelectorAll('.animate-element, .animate-left, .animate-right, .animate-scale');
  
  animatedElements.forEach(element => {
    const elementTop = element.getBoundingClientRect().top;
    const windowHeight = window.innerHeight;
    
    // 当元素进入视口时添加动画类，离开时移除
    if (elementTop < windowHeight * 0.8 && elementTop > -element.clientHeight) {
      if (!element.classList.contains('animate')) {
        element.classList.add('animate');
      }
    } else {
      element.classList.remove('animate');
    }
  });
}

// 监听滚动事件
window.addEventListener('scroll', handleScrollAnimation);

// 页面加载时初始检查
document.addEventListener('DOMContentLoaded', () => {
  handleScrollAnimation();
  
  // 设置当前年份
  const yearElement = document.getElementById('currentYear');
  if (yearElement) {
    yearElement.textContent = new Date().getFullYear();
  }
  
  // 图片画廊悬停效果
  const galleryItems = document.querySelectorAll('.gallery-item');
  galleryItems.forEach(item => {
    item.addEventListener('mouseenter', () => {
      item.style.transform = 'translateY(-10px)';
    });
    
    item.addEventListener('mouseleave', () => {
      item.style.transform = 'translateY(0)';
    });
  });
  
  // 成就卡片动画效果
  const achievementCards = document.querySelectorAll('.achievement-card');
  achievementCards.forEach(card => {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          card.style.transform = 'translateY(-10px) scale(1.02)';
        } else {
          card.style.transform = 'translateY(0) scale(1)';
        }
      });
    }, {
      threshold: 0.2
    });
    
    observer.observe(card);
  });
  
  // 活动卡片动画效果
  const activityCards = document.querySelectorAll('.activity-card');
  activityCards.forEach(card => {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          card.style.transform = 'translateY(-8px)';
        } else {
          card.style.transform = 'translateY(0)';
        }
      });
    }, {
      threshold: 0.2
    });
    
    observer.observe(card);
  });
});

// 平滑滚动
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
  anchor.addEventListener('click', function(e) {
    e.preventDefault();
    
    const targetId = this.getAttribute('href');
    if (targetId === '#') return;
    
    const targetElement = document.querySelector(targetId);
    if (targetElement) {
      // 考虑导航栏高度
      const navbarHeight = document.querySelector('.navbar').offsetHeight;
      const targetPosition = targetElement.getBoundingClientRect().top + window.pageYOffset - navbarHeight;
      
      window.scrollTo({
        top: targetPosition,
        behavior: 'smooth'
      });
      
      // 如果是移动端，点击后关闭菜单
      if (navLinks && navLinks.classList.contains('active')) {
        navLinks.classList.remove('active');
      }
    }
  });
});

// 表单提交处理
const contactForm = document.getElementById('contactForm');
if (contactForm) {
  contactForm.addEventListener('submit', (e) => {
    e.preventDefault();
    
    // 简单的表单验证
    const name = document.getElementById('name').value;
    const phone = document.getElementById('phone').value;
    const visitDate = document.getElementById('visit-date').value;
    
    if (!name || !phone || !visitDate) {
      alert('请填写姓名、联系电话和参观日期！');
      return;
    }
    
    // 模拟表单提交
    alert('预约提交成功！我们会尽快与您联系确认参观时间。');
    contactForm.reset();
  });
}

// 订阅表单处理
const newsletterForms = document.querySelectorAll('.newsletter-form');
newsletterForms.forEach(form => {
  form.addEventListener('submit', (e) => {
    e.preventDefault();
    
    const emailInput = form.querySelector('input[type="email"]');
    const email = emailInput.value;
    
    if (!email) {
      alert('请输入邮箱地址！');
      return;
    }
    
    // 简单的邮箱格式验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      alert('请输入有效的邮箱地址！');
      return;
    }
    
    alert('订阅成功！感谢您关注南皮文化遗产。');
    emailInput.value = '';
  });
});

// 数字动画效果
function animateNumber(number, finalValue) {
  const duration = 2000; // 2秒动画
  const startTime = performance.now();
  const startValue = 0;

  function updateNumber(currentTime) {
    const elapsed = currentTime - startTime;
    const progress = Math.min(elapsed / duration, 1);
    
    // 使用缓动函数
    const easeOutQuart = 1 - Math.pow(1 - progress, 4);
    const currentValue = startValue + (finalValue - startValue) * easeOutQuart;
    
    number.textContent = currentValue.toFixed(1);
    
    if (progress < 1) {
      requestAnimationFrame(updateNumber);
    } else {
      number.textContent = finalValue.toString();
    }
  }
  
  requestAnimationFrame(updateNumber);
}

function setupNumberAnimations() {
  const statNumbers = document.querySelectorAll('.stat-number');
  
  statNumbers.forEach(number => {
    const finalValue = parseFloat(number.textContent);
    
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          // 重置数值并重新开始动画
          number.textContent = '0';
          animateNumber(number, finalValue);
        }
      });
    }, {
      threshold: 0.5,
      rootMargin: '0px'
    });
    
    observer.observe(number);
  });
}

// 初始化数字动画
document.addEventListener('DOMContentLoaded', setupNumberAnimations);

// 时间轴动画增强
function enhanceTimelineAnimation() {
  const timelineItems = document.querySelectorAll('.timeline-item');
  
  timelineItems.forEach((item, index) => {
    item.style.animationDelay = `${index * 0.2}s`;
    
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          // 先移除类以重置动画
          entry.target.classList.remove('timeline-animate');
          // 强制重排
          void entry.target.offsetWidth;
          // 重新添加类触发动画
          entry.target.classList.add('timeline-animate');
        } else {
          entry.target.classList.remove('timeline-animate');
        }
      });
    }, {
      threshold: 0.2,
      rootMargin: '-50px'
    });
    
    observer.observe(item);
  });
}

// 添加时间轴动画CSS类
const timelineStyle = document.createElement('style');
timelineStyle.textContent = `
  .timeline-item {
    opacity: 0;
    transform: translateX(-30px);
    transition: all 0.6s ease-out;
  }
  
  .timeline-item.timeline-animate {
    opacity: 1;
    transform: translateX(0);
  }
`;
document.head.appendChild(timelineStyle);

// 初始化时间轴动画
document.addEventListener('DOMContentLoaded', enhanceTimelineAnimation);

// 添加页面加载完成后的欢迎提示
window.addEventListener('load', () => {
  // 延迟显示欢迎信息
  setTimeout(() => {
    console.log('欢迎访问南皮文化遗产网站！');
    console.log('探索张之洞纪念馆和大运河的历史文化');
  }, 1000);
});

// 页面加载后强制滚动到顶部，防止初始自动上滚
window.addEventListener('DOMContentLoaded', () => {
  setTimeout(() => {
    window.scrollTo({ top: 0, left: 0, behavior: 'auto' });
  }, 10);
});